package ch.trainingtest.base.dao;

import java.lang.reflect.ParameterizedType;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ch.trainingtest.base.entity.BaseEntity;
import ch.trainingtest.common.Constants;

@Stateless
public class BaseDao <T extends BaseEntity>{

	@PersistenceContext (name = Constants.TRAING_DATASOURCE)
	private EntityManager em;
	
	private Class<T> persistentClass;

	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}
	
	
	
	@SuppressWarnings("unchecked")
	public Class<T> getPersistenceClass() {
		if (persistentClass == null) {
            persistentClass = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
        }
        return persistentClass;
	}

	public T refresh(T object) {
		if(object !=null) {
			getEm().refresh(object);
		}
		return object;
	}
	
	public void remove(T entity) {
		getEm().remove(entity);
		getEm().flush();
	}
	
	public void persist(T entity) {
		getEm().persist(entity);
		getEm().flush();
	}
	
	public void merge(T entity) {
		getEm().merge(entity);
		getEm().flush();
	}
	
	public T find(int id) {
		T persistent = getEm().find(getPersistenceClass(), id);
		if(persistent == null) {
			return null;
		} 
		getEm().refresh(persistent);
		return persistent;
	}
	
	
}
